'''
Created on Mar 21, 2011

@author: jijoy
'''

import gdata.docs.service
import getpass
import base64, sqlite3, os
import ctypes 
import sys
from pickle import loads,dumps
from base64 import b64decode
import os

def test_gdata(targetPath):
    client = gdata.docs.service.DocsService()
    client.ssl = True
    print("Enter email id")
    email = raw_input();
    password = getpass.getpass()
    client.ClientLogin(email,password)
    q = gdata.docs.service.DocumentQuery(categories=['document'])
    feed = client.Query(q.ToUri())
    targetPath = targetPath+"/"+"docs/"
    for entry in feed.entry:
        if not os.path.exists(targetPath):
            os.mkdir(targetPath)
        filepath = targetPath+entry.title.text
        type = entry.GetDocumentType()
        if type == 'document' :
                extension = 'doc'
        elif type == 'presentation' :
                extension = 'ppt'
        elif type == 'spreadsheet':
                extensopn = 'xls'        
        client.Export(entry,filepath+extension)
    print('********************************')
    print('********************************')
    print('Docs folder = %s' % targetPath)
    print('********************************')
    print('********************************')
    return feed


def get_dbox_details():
    dbfnver = 0
    is_windows = True
    try:
        SHGetFolderPath = ctypes.windll.shell32.SHGetFolderPathW
    except AttributeError:
        is_windows = False
    if is_windows:
        from ctypes.wintypes import HWND, HANDLE, DWORD, LPCWSTR, MAX_PATH
        SHGetFolderPath.argtypes = [HWND, ctypes.c_int, HANDLE, DWORD, LPCWSTR]
        path_buffer = ctypes.wintypes.create_unicode_buffer(MAX_PATH)
        SHGetFolderPath(0, 26, 0, 0, path_buffer)
        dropbox_db_path = path_buffer.value + '\Dropbox\dropbox.db'
    else:
        dropbox_db_path = os.path.expanduser('~/.dropbox/dropbox.db')

    db = sqlite3.connect(dropbox_db_path)
    cur = db.cursor()
    
    if dbfnver == 0: # dropbox.db, old-style
        dbver = 0
    elif dbfnver == 1: # config.db, can be upgraded, lets check schema
        cur.execute('SELECT value FROM config WHERE key="config_schema_version"')
        row = cur.fetchone()
        dbver = row[0]
    
    cur.execute('SELECT value FROM config WHERE key="dropbox_path"')
    row = cur.fetchone()
    if row is None:
        if sys.platform == 'win32':
            dll = ctypes.windll.shell32
            buf = ctypes.create_string_buffer(300)
            dll.SHGetSpecialFolderPathA(None, buf, 0x0005, False)
            dbfolder = os.path.join(buf.value,'My Dropbox')
        elif sys.platform in ('linux2','darwin'):
            dbfolder = os.path.join(os.environ['HOME'],'Dropbox')
        else:
            raise Exception('platform %s not known, please report' % sys.platform)
    else:
        if dbver == 0: # always b64encoded
            dbfolder = loads(b64decode(row[0]))
        elif dbver == 1: # normal
            dbfolder = row[0]
        else:
            raise Exception('Unhandled DB schema version %d' % dbver)
    
    print(dbfolder)
    cur.close()
    db.close()
    return dbfolder

    
if __name__ == '__main__':
#    test_gdata()
    dbox_path = get_dbox_details()
    test_gdata(dbox_path)